﻿using AntdUI;
using BST250301.Models;
using BST250301TestStand.Models;
using BST250301TestStand.Models.Helpers;
using BST250301TestStand.Models.Utils;
using Microsoft.IdentityModel.Tokens;
using Mysqlx.Crud;
using Org.BouncyCastle.Crypto.Generators;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;


namespace BST250301.Views
{
    public partial class Login : AntdUI.Window
    {
        private static MainWindow mainWindow;
        internal static AppConfig configapp;
        public Login()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            InitializeComponent();
            InitData();
            this.AcceptButton = buttonADD;
            ShowTaskbar();

        }
        private void InitData()
        {
            configapp = new AppConfig().Load();
            configapp.DBConnectionServer = configapp.DBConnectionServer.Contains("Pwd=W1717@sina.com;") ? configapp.DBConnectionServer : configapp.DBConnectionServer + "Pwd=W1717@sina.com;";
            configapp.DBConnectionServer = configapp.DBConnectionServer.Replace("Port=3306", $"Port={configapp.DBPort}");

            var result = DB.GetPlanName(configapp.DBConnectionServer);
            if (result != null)
            {
                selectPlanName.Items.Clear();
                foreach (var item in result)
                {
                    selectPlanName.Items.Add(item.PlanName);
                }
                selectPlanName.Items.Add("新建方案名");
            }
        }
        // 捕获UI线程中的未处理异常
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            AntdUI.Notification.error(mainWindow, "未处理的UI线程异常", e.Exception.Message, autoClose: 3, align: AntdUI.TAlignFrom.TR);
        }

        // 捕获非UI线程中的未处理异常
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            AntdUI.Notification.error(mainWindow, "未处理的非UI线程异常", e.ToString(), autoClose: 3, align: AntdUI.TAlignFrom.TR);
        }

        private void buttonADD_Click_1(object sender, EventArgs e)
        {
            string username = inputName.Text.Trim();
            string password = inputPassword.Text;
            if (string.IsNullOrEmpty(selectPlanName.Text))
            {
                MessageBox.Show($"方案名不可为空！");
                return;
            }
            try
            {
                //string encryptedString = AesEncryptor.Encrypt("2025-10-26 11:20:00");
                // 加密密码（生成哈希，自动包含盐）
                // string hashedPassword = BCrypt.Net.BCrypt.HashPassword("admin");
                //string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password);
                //string hashedDatetime = BCrypt.Net.BCrypt.HashPassword("2025-10-26 10:20:00");
                var userCurrent = DB.GetUserData(configapp.DBConnectionServer, username);
                inputPassword.Clear();
                //var verify = BCrypt.Net.BCrypt.Verify(password, userCurrent.Password);
                if (userCurrent.Password == password)
                {
                    string decryptedString = AesEncryptor.Decrypt(userCurrent.AuthorizeHash);
                    DateTime.TryParse(decryptedString, out DateTime dtend);

                    TimeSpan difference = dtend.Subtract(DateTime.Now);
                    int lastday = (int)difference.TotalDays;
                    if (lastday < 1)
                    {
                        //AntdUI.Notification.error(this, "System Error", "", autoClose: 5, align: AntdUI.TAlignFrom.TR);
                        userCurrent.ApprovalEnable = false;
                    }
                    else
                        userCurrent.ApprovalEnable = true;

                    configapp.PlanName = selectPlanName.Text.Trim();
                    mainWindow = new MainWindow(configapp, userCurrent, dtend);
                    mainWindow.Show();
                    this.Hide(); // 隐藏登录窗体
                }
                else
                {
                    MessageBox.Show($"密码错误");
                    return;
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show("无效的授权信息，请联系管理员H");
            }
        }
        private Oper GetUserData(string username)
        {
            var user = new Oper() { Account = "admin", };

            return user;
        }
        private void buttonDEL_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
            //Application.Exit(); // 退出程序
        }

        private void panel1_Click(object sender, EventArgs e)
        {

        }
        [DllImport("user32.dll")]
        private static extern int FindWindow(string className, string windowText);

        [DllImport("user32.dll")]
        private static extern int ShowWindow(int hwnd, int command);

        public static void HideTaskbar()
        {
            int taskbarHandle = FindWindow("Shell_TrayWnd", "");
            ShowWindow(taskbarHandle, 0);

            int startButtonHandle = FindWindow("Button", "Start");
            ShowWindow(startButtonHandle, 0);
        }

        public static void ShowTaskbar()
        {
            int taskbarHandle = FindWindow("Shell_TrayWnd", "");
            ShowWindow(taskbarHandle, 5);

            int startButtonHandle = FindWindow("Button", "Start");
            ShowWindow(startButtonHandle, 5);
        }
    }
}
